<?php

use App\Enums\AssetSourceType;
use App\Enums\AssetStatus;
use App\Models\Asset;
use App\Models\FrontendUser;
use App\Services\WalletService;

require __DIR__ . '/../vendor/autoload.php';

$app = require_once __DIR__ . '/../bootstrap/app.php';

$app->make(\App\Console\Kernel::class)->bootstrap();

/* ============== Write Codes Below ================= */

echo '>>> Start Laravel from CLI' . PHP_EOL;

/** @var WalletService $walletService */
$walletService = app()->get(WalletService::class);

$agentId = 3;

// token_id, owner_mobile, to_mobile
$data = [
    ['[token_id]4131964148154023659429967118092763460482516453561809589496257670', '15313035650', '18810454250'],
];

foreach ($data as $row) {
    $tokenId = str_replace('[token_id]', '', trim($row[0]));
    $fromMobile = trim($row[1]);
    $toMobile = trim($row[2]);

    /** @var Asset $asset */
    $asset = Asset::query()
        ->where('token_id', $tokenId)
        ->where('asset_status', AssetStatus::HOLD)
        ->first();

    if (!$asset) {
        echo sprintf('资产【%s】未找到', $tokenId) . PHP_EOL;

        continue;
    }

    /** @var FrontendUser $fromUser */
    $fromUser = FrontendUser::query()->where('agent_id', $agentId)->where('mobile', $fromMobile)->first();
    /** @var FrontendUser $toUser */
    $toUser = FrontendUser::query()->where('agent_id', $agentId)->where('mobile', $toMobile)->first();
    if (!$fromUser) {
        echo sprintf('手机号%s对应的用户未找到', $fromMobile);
    }
    if (!$toUser) {
        echo sprintf('手机号%s对应的用户未找到', $toMobile);
    }

    if ($asset->user_id == $toUser->id) {
        echo sprintf('资产【%s】已经属于%s', $tokenId, $toUser->mobile) . PHP_EOL;

        continue;
    }
    if ($asset->user_id != $fromUser->id) {
        echo sprintf('资产【%s】不属于%s', $tokenId, $fromUser->mobile) . PHP_EOL;

        continue;
    }
    DB::transaction(function () use ($asset, $walletService, $fromMobile, $tokenId, $toUser) {
        $asset->asset_status = AssetStatus::GIVE;
        $asset->save();
        $transResult = $walletService->transfer(
            $fromMobile,
            $asset->contract_address,
            [$tokenId],
            $toUser->wallet_address
        );
        $transHash = Arr::get($transResult, $tokenId);
        if (!$transHash) {
            echo sprintf('资产【%s】转账返回值错误', $tokenId) . PHP_EOL;

            return;
        }

        $toAsset = new Asset();
        $toAsset->user_id = $toUser->id;
        $toAsset->source_type = AssetSourceType::GIVE;
        $toAsset->source_id = $asset->id;
        $toAsset->contract_address = $asset->contract_address;
        $toAsset->token_id = $asset->token_id;
        $toAsset->trans_hash = $transHash;
        $toAsset->asset_status = AssetStatus::HOLD;
        $toAsset->save();

        echo sprintf('资产【%s】成功转移给 %s', $tokenId, $toUser->mobile) . PHP_EOL;
    });
}
